<template>
  <div class="audio-library-wrap">
    <div class="detail-wrap">
      <p class="warn-text" v-if="showBread ==='addVoice'">{{$t('config.channel.addVoiceWarnText')}}</p>
      <el-form :model="callAudioFrom" :rules="rules" ref="callAudioFrom" label-width="130px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('config.channel.voiceFiledType')" prop="SoundType">
              <!--showBread === 'addVoice'?false:true   添加录音的时候可以编辑，其他情况下都是不可编辑-->
              <el-select size="mini" v-model="callAudioFrom.SoundType" :placeholder="$t('public.pleasePick')" :disabled="showBread === 'addVoice'?false:true" class="select">
                <el-option
                        v-for="item in soundType"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value"
                        >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('config.channel.voiceFiledNames')" prop="DisplayName">
              <el-input size="mini"  v-model.trim="callAudioFrom.DisplayName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="!isSimpleConfig">
          <el-col>
            <el-form-item label="PBX" prop="PBX">
              <el-select size="mini" v-model="callAudioFrom.PBX" :placeholder="$t('public.pleasePick')" :disabled="showBread === 'addVoice'?false:true" class="select">
                <el-option
                        v-for="(item,index) in allPbxs"
                        :label="item.NickName + ' (' +item.PBX + ')'"
                        :value="item.PBX"
                        :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="showBread === 'addVoice'">
          <el-col>
            <el-form-item :label="$t('config.channel.voiceFiled')" prop="upload">
              <el-upload
                      :action="uploadUrl"
                      :data="uploadHeaders"
                      name="upload"
                      :with-credentials="true"
                      :on-success="uploaded"
                      :on-error="uploadError"
                      :on-remove="removeUploadList"
                      ref="upload"
                      >
                <el-button size="small" class="primary_btn">{{$t('config.channel.choiceFiled')}}</el-button>
              </el-upload>
              <div class="upload-text" v-text="uploadText"></div>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="showBread !== 'addVoice' ">
          <audio-common flagId="audio_library" :isAutoPlay="false" :srcUrl="callAudioFrom.fileUrl" :isShowAudioDownload="true" :isShowSubmitAudio="false" :changeStyle="'width:300px;'" :currentObj="{}" :isShowSelect="false" :isConfig="true"></audio-common>
        </div>
        <el-row :gutter="20">
          <el-col>
            <el-form-item :label="$t('config.channel.voiceFiledExplain')" prop="Memo">
              <el-input size="mini" type="textarea" v-model="callAudioFrom.Memo" :maxlength="50"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="!isSimpleConfig" class="fr btn-group">
        <!--<el-button class="primary_btn" @click.stop="cancle()">{{$t('public.cancel')}}</el-button>-->
        <el-button type="primary" class="primary_btn" @click.stop="save(callAudioFrom)">{{$t('public.save')}}</el-button>
      </div>
      <div v-if="isSimpleConfig" class="footer">
        <el-button class='slide-box__button' @click='cancle'>
          {{$t('public.cancel')}}
        </el-button>
        <el-button class='slide-box__button' type="primary" @click.stop="save(callAudioFrom)">
          {{$t('public.save')}}
        </el-button>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :title="$t('channelsettings.Voicelibrary1')" :visible="soundTransferWait" :show-close="false" :append-to-body='true'>
      <h4 v-text="warnText"></h4>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadTransferCancel"  v-if="soundTransferBtn"  class="primary_btn">{{$t('channelsettings.Voicelibrary2')}}</el-button>
        <el-button @click="uploadTransferRefresh"  v-if="soundTransferBtn" type="primary" class="primary_btn">{{$t('channelsettings.Voicelibrary3')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import AudioCommon from '@/components/public-modules/audio/audio.vue'
  export default {
    name: 'callAudioDetail',
    data () {
      return {
        rules: {
          DisplayName: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          PBX: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          SoundType: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
        },
        soundType: [{value: 'normal', name: this.$t('config.channel.ordinary')}, {value: 'hold', name: this.$t('config.channel.voiceOfQueueWaiting')}],
        uploadUrl: '/fileUpload',
        allPbxs: this.$store.state.session.account.pbx || [],
        uploadHeaders: {
          type: 'undefined',
          module: '',
          sessionId: this.$store.state.session.sessionId
        },
        isShowUploadWait: false,
        warnText: '', // 上传弹窗的温馨提示
        soundTransfer: false, // 转换超时的按钮
        persistentId: '',
        uploadText: '', // 上传的温馨提示
        soundTransferWait: false, // 语音转换弹窗
        IsQiniuMusic: '', // 上传到七牛的文件
        QiniuMusicUrl: '', // 七牛文件url
        lastUrl: '', // 最后的上传文件
        firstUrl: ''
      }
    },
    props: {
      showBread: String,
      currentData: {
        type: Object,
        default: function () {
          return {}
        }
      },
      isRestFrom: Number,
      isSimpleConfig: {
        type: Boolean,
        default: function () {
          return false
        }
      }
    },
    methods: {
      cancle () {
        this.$emit('cancle')
      },
      save (form) {
        this.$refs['callAudioFrom'].validate((valid) => {
          if (valid) {
            let data = {}
            if (this.showBread !== 'addVoice') { // 编辑
              data._id = form._id
              data.SoundFilePath = form.Filename || ''
              data.OldSoundFilePath = form.OldSoundFilePath || ''
            } else { // 添加
              if (!this.lastUrl) {
                this.$message.error(this.$t('channelsettings.Voicelibrary4'))
                return
              }
              data.SoundFilePath = this.firstUrl
              data.OldSoundFilePath = ''
              data.IsQiniuMusic = this.IsQiniuMusic
              data.QiniuMusicUrl = this.QiniuMusicUrl
            }
            data.SoundType = form.SoundType || ''
            data.DisplayName = form.DisplayName || ''
            data.Memo = form.Memo || ''
            data.Account = form.Account
            data.PBX = form.PBX
            if (this.isSimpleConfig) {
//              简单设置
              data.PBX = this.PBX
            }
            this.$store.dispatch('updateSound', data).then(resp => {
              if (resp.success) {
                this.$emit('resh', data.PBX)
                this.$emit('cancle')
                this.$message.success(this.$t('channelsettings.Voicelibrary5'))
              } else {
                this.$message.error(this.$t('channelsettings.Voicelibrary6'))
              }
            })
          }
        })
      },
      uploaded (response, file, fileList) {
        if (response) {
          if (response.filePath) {
            this.uploadText = this.$t('channelsettings.Voicelibrary7')
            this.firstUrl = response.filePath
            this.IsQiniuMusic = ''
            this.QiniuMusicUrl = '' // 重置，不然添加完不是wav的音频文件之后，再上传wav文件会有问题
            this.OldSoundFilePath = ''
            let fileName = /[^.]+$/.exec(response.fileName)
            if (fileName && fileName[0] !== 'wav') { // 不是wav的格式
              this.uploadText = this.$t('channelsettings.Voicelibrary8')
              this.warnText = this.$t('channelsettings.Voicelibrary9')
              this.soundTransferWait = true
              this.soundTransfer = false // 解决第一次展示按钮之后，下次再次打开音频转换直接出来了
              this.$store.dispatch('soundToQiniuTransfer', response).then(resp => {
                if (resp.success) {
                  this.uploadText = this.$t('channelsettings.Voicelibrary10')
                  this.persistentId = resp.data.persistentId
                  let self = this
                  window.setTimeout(function () {
                    self.soundTransfer = true
                  }, 15000)
                } else {
                  this.soundTransferWait = false
                  this.$refs.upload.clearFiles()
                  this.lastUrl = ''
                  this.uploadText = this.$t('channelsettings.Voicelibrary11')
                }
              })
            } else {
              this.lastUrl = response.filePath
            }
          } else {
            this.$refs.upload.clearFiles()
            this.lastUrl = ''
            this.uploadText = this.$t('channelsettings.Voicelibrary12')
          }
        }
      },
      uploadTransferRefresh () { // 再次尝试语音上传到七牛来转换成wav
        let data = {persistentId: this.persistentId}
        this.$store.dispatch('soundToQiniuTransferRefresh', data).then(resp => {
          if (resp.success) {
            if (resp.code === 0) {
              this.soundTransferWait = false
              this.IsQiniuMusic = 'yes'
              this.QiniuMusicUrl = resp.url
              this.lastUrl = resp.url
              this.uploadText = this.$t('channelsettings.Voicelibrary13')
            } else {
              this.$message(this.$t('channelsettings.Voicelibrary14'))
            }
          } else {
            this.$refs.upload.clearFiles()
            this.lastUrl = ''
            this.soundTransferWait = false
            this.uploadText = this.$t('channelsettings.Voicelibrary15')
          }
        })
      },
      uploadTransferCancel () { // 不等了，放弃这次，重新来过
        this.$emit('reshAdd')
        this.soundTransferWait = false
        this.uploadText = ''
        this.$refs.upload.clearFiles()
        this.lastUrl = ''
      },
      uploadError () {
        this.$refs.upload.clearFiles()
        this.lastUrl = ''
        this.uploadText = this.$t('channelsettings.Voicelibrary16')
      },
      removeUploadList () {
        this.$refs.upload.clearFiles()
        this.uploadText = ''
        this.lastUrl = ''
      }
    },
    computed: {
      callAudioFrom () {
        if (this.showBread === 'addVoice') {
          if (this.$refs.upload) {
            this.$refs.upload.clearFiles()
            this.lastUrl = ''
          }
          this.uploadText = ''
        }
        return this.currentData || {}
      },
      ivrSoundTransfer () {
        return this.$store.state.ivrSoundTransfer
      },
      soundTransferBtn () {
        return this.soundTransfer
      },
      PBX () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    watch: {
      ivrSoundTransfer (pushEvent) {
        if (this.persistentId === pushEvent.Data.persistentId) {
          this.soundTransferWait = false
          if (pushEvent.Data.code === 0) {
            this.IsQiniuMusic = 'yes'
            this.QiniuMusicUrl = pushEvent.Data.url
            this.lastUrl = pushEvent.Data.url
            this.uploadText = this.$t('channelsettings.Voicelibrary17')
          } else {
            this.$refs.upload.clearFiles()
            this.lastUrl = ''
            this.uploadText = this.$t('channelsettings.Voicelibrary18')
          }
        }
      },
      isRestFrom () {
        if (this.$refs.callAudioFrom) {
          this.$refs.callAudioFrom.resetFields() // 表单重置
        }
      }
    },
    components: {
      AudioCommon
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .detail-wrap
     padding 20px
     .select
       width 100%
     .warn-text
       padding-bottom 20px
       color $c-prompt
     .btn-group
       margin 20px 0 30px
  .upload-text
     color $c-main
     font-size 12px
  .footer
    position absolute
    bottom 0
    left 0
    width 100%
    background rgba(255,255,255,1)
    box-shadow 0px -2px 4px 0px rgba(5,49,38,0.05)
    border-top 1px solid rgba(232,232,232,1)
    display flex
    justify-content center
    padding 13px 0
    box-sizing border-box
    .slide-box__button
      padding 8px 20px 8px
      box-sizing border-box
</style>
